package com.linksfield.topup.service.impl;

import com.alibaba.fastjson.JSON;
import com.linksfield.topup.config.dto.CalculateResultParamVo;
import com.linksfield.topup.config.dto.PageAndSort;
import com.linksfield.topup.config.dto.ResultDataDto;
import com.linksfield.topup.config.dto.StringOutputConstant;
import com.linksfield.topup.entity.common.ServicePlanOrderAutoRenewalRecord;
import com.linksfield.topup.entity.interfaces.autosubmanage.search.request.RequestAutoSubscriptionSearch;
import com.linksfield.topup.entity.interfaces.autosubmanage.search.response.ResponseAutoSubCount;
import com.linksfield.topup.entity.interfaces.autosubmanage.search.response.ResponseAutoSubscription;
import com.linksfield.topup.entity.interfaces.autosubmanage.search.response.ResponseAutoSubscriptionSearch;
import com.linksfield.topup.mapper.AutoSubscriptionMapper;
import com.linksfield.topup.service.AutoSubscriptionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lm
 * @date 2021/7/2 10:11
 */
@Service
@Slf4j
public class AutoSubscriptionServiceImpl implements AutoSubscriptionService {
    /**
     * 调用公用的方法
     */
    @Autowired
    CommonUtilsServiceImpl utilsService;
    /**
     * 调用操作数据库表的mapper类
     */
    @Resource
    private AutoSubscriptionMapper autoSubscriptionMapper;
    /**
     *
     */
    SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 自动订阅管理：搜索
     *
     * @param request
     * @param token
     * @return
     */
    @Override
    public ResultDataDto search(RequestAutoSubscriptionSearch request, String token) {
        if (StringUtils.isBlank(token)) {
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_TOKEN_EMPTY);
        }
        //1,先去公共服务类验证token
        String results = utilsService.checkToken(token);
        if (StringUtils.isBlank(results) || !StringOutputConstant.CODE_SUCCESS.equals(results)) {
            // 验证token出现问题，直接返回
            return ResultDataDto.addOperationFailure(results);
        }
        //确认安全，开始验证参数
        if (StringUtils.isBlank(request.getTradeType()) || StringUtils.isBlank(request.getLang()) ||
                StringUtils.isBlank(request.getVersion()) || null == request.getPartnerCode() ||
                null == request.getCondition() || null == request.getStatus() ||
                null == request.getRp() || null == request.getCurrentPage()) {
            // 上报的参数有误
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PARAM_ERROR);
        }

        /*先去把总条数拿到*/
        long rowCount = autoSubscriptionMapper.searchPageCount(request);
        /*分页内容：包含页码，每页显示行数，总条数*/
        PageAndSort pageHelper = utilsService.buildUpPageAndSort(request.getRp(), request.getCurrentPage(), rowCount);

        /*计算服务总条数，生效条数，失效条数*/
        List<CalculateResultParamVo> countList = autoSubscriptionMapper.calculate(request);
        Map<String, Integer> map = new HashMap<>();
        for (CalculateResultParamVo vo : countList) {
            map.put(vo.getStatus(), vo.getCounts());
        }
        Integer key1 = 0;
        Integer key2 = 0;
        for (String key : map.keySet()) {
            if ("active".equals(key)) {
                key1 = map.get(key);
            }
            if ("canceled".equals(key)) {
                key2 = map.get(key);
            }
        }
        ResponseAutoSubCount count = new ResponseAutoSubCount();
        count.setTotalCount(key1 + key2);
        count.setValidCount(key1);
        count.setInvalidCount(key2);

        /*自动续费服务列表*/
        List<ServicePlanOrderAutoRenewalRecord> recordList = autoSubscriptionMapper.search(request, pageHelper);
        List<ResponseAutoSubscription> autoSubList = new ArrayList<>();
        if (null != recordList && !recordList.isEmpty()) {
            for (ServicePlanOrderAutoRenewalRecord record : recordList) {
                ResponseAutoSubscription autoSub = new ResponseAutoSubscription();
                autoSub.setPayId(record.getPayId());
                autoSub.setDeviceCode(record.getDeviceCode());
                autoSub.setSubId(record.getSubId());
                autoSub.setIntervals(utilsService.setIntervals(record.getIntervals(), record.getIntervalCount()));
                autoSub.setAmount(record.getAmount());
                autoSub.setCurrency(record.getCurrency());
                autoSub.setStatus(utilsService.setStatus(record.getStatus()));
                autoSub.setPartnerName(autoSubscriptionMapper.getPartnerName(record.getPartnerCode()));
                try {
                    autoSub.setSubscriptionDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(s.parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(record.getCreateDate()))));
                } catch (Exception e) {
                    autoSub.setSubscriptionDate("-");
                }
                autoSubList.add(autoSub);
            }
        }
        /*组装数据响应*/
        ResponseAutoSubscriptionSearch response = new ResponseAutoSubscriptionSearch();
        response.setAutoSubCount(count);
        response.setAutoSubList(autoSubList);
        log.info("【自动订阅管理搜索】响应:" + JSON.toJSONString(response));
        /*响应*/
        return ResultDataDto.addOperationSuccess().setData(response).setPageAndSort(pageHelper);
    }
}
